var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('hbs');

var global = require('./common/global');
var routes = require('./routes/index');
var log4js = require('log4js');
var logger = require('./common/config').logger('app');

var app = express();

//1. driver client -info-> server , push socket to array.
//1. custom client -info-> server , push cus socket by order
//2. custom generate order -info-> client[sockets]{filter by driver_info}
//3. driver -emit fetch-> server logic -> emit to custom
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
    socket.on('online', function (data) {
        logger.info("Driver Connected. ID : "+ data.id);
        global.sockets[data.id] = socket;
        global.drivers[data.id] = data;
        global.handOutToDriver(data.id);
    });
    socket.on('changeStatus', function (data) {
        logger.info("Driver Change Status. ID : "+ data.id + "," + data.running);
        global.drivers[data.id].status = data.running;
    });
    socket.on('grab',function(data){
        socket.emit("grabResult"+global.grabOrder(data));
    });
    socket.on('customOnline',function(data) {
        global.customers[data.id] = socket;
        console.log(data.id);
    });
});

// view engine setup
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
//hbs.registerHelper('helper_name', function) {});
hbs.registerPartials(__dirname + '/views');
//app.set('views', path.join(__dirname, 'views'));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(log4js.connectLogger(logger, {level: 'auto', format: ':method :url'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

routes(app);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        logger.error(err);
        res.render('error.hbs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error.hbs', {
        message: err.message,
        error: {}
    });
});

process.on('uncaughtException', function (err) {
    logger.fatal(err);
});

module.exports = app;
